<template>
  <div class="payment-type-selector">
    <!-- 触发区域 -->
    <div class="selector-trigger" :class="{ 'has-error': hasError }" @click="openModal">
      <div class="trigger-content">
        <span v-if="!selectedSummary" class="placeholder">请选择结算方式并分配金额</span>
        <span v-else class="selected-text">{{ selectedSummary }}</span>
        <right-outlined class="arrow-icon" />
      </div>
    </div>

    <!-- 结算方式分配弹窗 -->
    <a-modal v-model:visible="visible" title="选择结算方式并分配金额" width="680px" :maskClosable="false" @ok="handleConfirm" @cancel="handleCancel">
      <div class="modal-content">
        <!-- 总金额与剩余金额提示 -->
        <div class="amount-summary">
          <div class="summary-item">
            <span class="label">订单金额：</span>
            <span class="value" style="color: #1890ff">{{ orderAmount }} 元</span>
          </div>
          <div class="summary-item">
            <span class="label">已分配金额：</span>
            <span class="value" :style="{ color: assignedAmountExceedsOrder ? '#ff4d4f' : '#52c41a' }"> {{ assignedAmount }} 元 </span>
          </div>
          <div class="summary-item">
            <span class="label">剩余金额：</span>
            <span class="value" :style="{ color: remainingAmountIsNegative ? '#ff4d4f' : '#666' }"> {{ remainingAmount }} 元 </span>
          </div>
          <div class="summary-item">
            <span class="label">预付款账户余额：</span>
            <span class="value" :style="{ color: accountBalanceIsInsufficient ? '#ff4d4f' : '#52c41a' }"> {{ accountBalance }} 元 </span>
          </div>
        </div>

        <!-- 结算方式列表 -->
        <div class="payment-allocation-list">
          <div
            class="payment-item"
            v-for="option in paymentOptions"
            :key="option.value"
            :class="{
              selected: isPaymentSelected(option.value),
              disabled: isPaymentDisabled(option.value)
            }"
          >
            <!-- 复选框 -->
            <div class="checkbox-wrapper">
              <a-checkbox :checked="isPaymentSelected(option.value)" :disabled="isPaymentDisabled(option.value)" @change="(e) => handlePaymentCheck(e.target.checked, option)">
                <span class="payment-name">
                  {{ option.label }}
                  <span class="status-badge" v-if="isPaymentSelected(option.value)"> 已选 </span>
                </span>
              </a-checkbox>
            </div>

            <!-- 金额输入区域（选中时才显示） -->
            <div class="amount-input-wrapper" v-if="isPaymentSelected(option.value)">
              <!-- 可编辑项：现结、欠款、预付款 -->
              <template v-if="['CASH', 'CREDIT', 'PREPAY'].includes(option.value)">
                <span class="input-label">金额：</span>
                <a-input-number v-model:value="getPaymentDetail(option.value).amount" :min="option.value === 'PREPAY' ? 1 : 0" :max="getMaxAmount(option.value)" :precision="2" style="width: 140px" @change="(val) => handleAmountChange(val, option.value)" />
                <!-- <a-input-number v-model:value="getPaymentDetail(option.value).amount" :min="option.value === 'PREPAY' ? 1 : 0" :max="getMaxAmount(option.value)" :precision="2" style="width: 140px" @change="() => validateAmount(option.value)" /> -->
                <span class="unit">元</span>

                <!-- 预付款余额提示 -->
                <span v-if="option.value === 'PREPAY' && accountBalanceIsInsufficient" class="balance-tip"> 账户余额：{{ accountBalance }} 元 </span>
              </template>

              <!-- 独占项（0元增/押金）：禁用输入框 -->
              <template v-else>
                <span class="input-label">金额：</span>
                <a-input-number :value="option.value === 'ZERO' ? 0 : orderAmount" disabled style="width: 140px" />
                <span class="unit">元</span>
                <span class="system-tip">（系统自动处理）</span>
              </template>
            </div>

            <!-- 预付款余额不足警告 -->
            <div v-if="option.value === 'PREPAY' && isPaymentSelected(option.value) && isPrepayAmountExceedingBalance(option.value)" class="balance-warning-inline">
              <exclamation-circle-filled style="color: #ff4d4f; margin-right: 4px" />
              <span style="color: #ff4d4f; font-size: 12px">预付款金额超过账户余额</span>
            </div>

            <!-- 预付款余额为0时的禁用提示 -->
            <div v-if="option.value === 'PREPAY' && accountBalance === 0" class="balance-warning-inline">
              <exclamation-circle-filled style="color: #ff4d4f; margin-right: 4px" />
              <span style="color: #ff4d4f; font-size: 12px">账户余额为0，无法选择</span>
            </div>
          </div>
        </div>

        <!-- 底部提示信息 -->
        <div class="validation-message" v-if="validationMessage">
          <exclamation-circle-filled style="color: #ff4d4f; margin-right: 8px" />
          <span style="color: #ff4d4f">{{ validationMessage }}</span>
        </div>
      </div>

      <template #footer>
        <a-button @click="handleCancel">取消</a-button>
        <a-button type="primary" @click="handleConfirm" :disabled="!canConfirm" :loading="confirmLoading"> 确定（{{ selectedCount }}/2） </a-button>
      </template>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { RightOutlined, ExclamationCircleFilled } from '@ant-design/icons-vue'
import BigNumber from 'bignumber.js'

// Props
const props = defineProps({
  value: { type: Array, default: () => [] },
  orderAmount: { type: Number, default: 0 },
  accountBalance: { type: Number, default: 0 },
  hasError: { type: Boolean, default: false }
})

// Events
const emit = defineEmits(['update:value', 'change'])

// 结算方式枚举
const paymentOptions = [
  { label: '现结', value: 'CASH', paytype: 1 },
  { label: '欠款', value: 'CREDIT', paytype: 2 },
  { label: '预付款', value: 'PREPAY', paytype: 3 },
  { label: '0元赠', value: 'ZERO', paytype: 4 },
  { label: '押金', value: 'DEPOSIT', paytype: 5 }
]

// 弹窗状态
const visible = ref(false)
const confirmLoading = ref(false)
const validationMessage = ref('')

// 弹窗内部数据（核心：初始必须为空数组）
const modalPaymentDetails = ref([])

// 选中数量
const selectedCount = computed(() => modalPaymentDetails.value.length)

// 已分配金额（仅计算可编辑项）
const assignedAmount = computed(() => {
  return modalPaymentDetails.value
    .filter((item) => ['CASH', 'CREDIT', 'PREPAY'].includes(item.value))
    .reduce((sum, item) => sum.plus(item.amount || 0), new BigNumber(0))
    .toNumber()
})

// 剩余金额
const remainingAmount = computed(() => {
  return new BigNumber(props.orderAmount).minus(assignedAmount.value).toNumber()
})

// 比较标志计算属性
const assignedAmountExceedsOrder = computed(() => {
  return new BigNumber(assignedAmount.value).gt(props.orderAmount)
})

const remainingAmountIsNegative = computed(() => {
  return new BigNumber(remainingAmount.value).lt(0)
})

const accountBalanceIsInsufficient = computed(() => {
  return new BigNumber(props.accountBalance).lt(props.orderAmount)
})

// 获取最大金额（用于输入框限制）
const getMaxAmount = (value) => {
  if (value === 'PREPAY') {
    return BigNumber.min(props.orderAmount, props.accountBalance).toNumber()
  }
  return new BigNumber(props.orderAmount).toNumber()
}

// 检查预付款是否超额
const isPrepayAmountExceedingBalance = (value) => {
  const detail = getPaymentDetail(value)
  return detail ? new BigNumber(detail.amount).gt(props.accountBalance) : false
}

// 是否可以确认
const canConfirm = computed(() => {
  if (selectedCount.value === 0) return false

  // 独占项（0元增/押金）只能单独选择
  const exclusiveItems = modalPaymentDetails.value.filter((item) => ['ZERO', 'DEPOSIT'].includes(item.value))
  if (exclusiveItems.length > 0) {
    return selectedCount.value === 1
  }

  // 预付款校验
  const prepayItem = modalPaymentDetails.value.find((item) => item.value === 'PREPAY')
  if (prepayItem) {
    if (new BigNumber(prepayItem.amount).lte(0)) return false
    if (new BigNumber(prepayItem.amount).gt(props.accountBalance)) return false
  }

  // 非独占项金额必须完全分配
  return new BigNumber(remainingAmount.value).isEqualTo(0)
})

// 触发区域显示文本（使用逗号分隔）
const selectedSummary = computed(() => {
  if (!props.value || props.value.length === 0) return ''
  return props.value
    .map((item) => {
      const option = paymentOptions.find((opt) => opt.paytype === item.paytype)
      return option ? `${option.label}: ${item.amount}元` : ''
    })
    .filter(Boolean)
    .join(', ')
})

// 判断是否选中
const isPaymentSelected = (value) => {
  return modalPaymentDetails.value.some((item) => item.value === value)
}

// 判断是否禁用（修复核心逻辑）
const isPaymentDisabled = (value) => {
  // 如果已选中独占项（0元增/押金）
  const selectedExclusive = modalPaymentDetails.value.find((item) => ['ZERO', 'DEPOSIT'].includes(item.value))
  if (selectedExclusive) {
    // 只有已选中的独占项可操作，其他全部禁用
    return value !== selectedExclusive.value
  }

  // 如果是未选中的独占项，且已选了其他项，则禁用
  if (!isPaymentSelected(value) && modalPaymentDetails.value.length > 0 && ['ZERO', 'DEPOSIT'].includes(value)) {
    return true
  }

  // 预付款余额为0时禁用
  if (value === 'PREPAY' && props.accountBalance <= 0) {
    return true
  }

  // 最多2个限制
  if (modalPaymentDetails.value.length >= 2) {
    return !isPaymentSelected(value)
  }

  return false
}

// 获取支付详情（修复：只读，不自动添加）
const getPaymentDetail = (value) => {
  return modalPaymentDetails.value.find((item) => item.value === value)
}

// 创建新的支付详情（修复：不自动push）
const createPaymentDetail = (value) => {
  const option = paymentOptions.find((opt) => opt.value === value)
  let defaultAmount = 0

  if (value === 'PREPAY') {
    defaultAmount = BigNumber.min(props.orderAmount, props.accountBalance).toNumber()
  } else if (value === 'CASH' || value === 'CREDIT') {
    defaultAmount = new BigNumber(remainingAmount.value).gt(0) ? remainingAmount.value : 0
  } else if (value === 'ZERO') {
    defaultAmount = 0
  } else if (value === 'DEPOSIT') {
    defaultAmount = new BigNumber(props.orderAmount).toNumber()
  }

  return {
    value: value,
    paytype: option.paytype,
    label: option.label,
    amount: defaultAmount
  }
}

// 处理复选框变化（修复：手动管理数组）
const handlePaymentCheck = (checked, option) => {
  if (checked) {
    // 手动创建并添加到数组
    const newDetail = createPaymentDetail(option.value)
    modalPaymentDetails.value.push(newDetail)
  } else {
    // 从数组中移除
    const index = modalPaymentDetails.value.findIndex((item) => item.value === option.value)
    if (index > -1) {
      modalPaymentDetails.value.splice(index, 1)
    }
  }
  validateAll()
}

// 验证金额
const validateAmount = () => {
  validateAll()
}

// 处理金额输入变化（修复空值变成NaN的问题）
const handleAmountChange = (val, value) => {
  const detail = getPaymentDetail(value)
  if (detail) {
    // 如果值为null、undefined或空字符串，则设为0
    detail.amount = val == null || val === '' ? 0 : val
  }
  validateAll()
}

// 全局验证
const validateAll = () => {
  validationMessage.value = ''

  if (modalPaymentDetails.value.length === 0) {
    validationMessage.value = '请至少选择一种结算方式'
    return
  }

  // 独占项互斥校验
  const exclusiveCount = modalPaymentDetails.value.filter((item) => ['ZERO', 'DEPOSIT'].includes(item.value)).length
  if (exclusiveCount > 0 && modalPaymentDetails.value.length > 1) {
    const exclusiveName = modalPaymentDetails.value.find((item) => ['ZERO', 'DEPOSIT'].includes(item.value))?.label
    validationMessage.value = `${exclusiveName}不能与其他结算方式组合`
    return
  }

  // 预付款余额为0时不能选中
  if (modalPaymentDetails.value.some((item) => item.value === 'PREPAY') && props.accountBalance <= 0) {
    validationMessage.value = '预付款账户余额为0，无法选择预付款'
    return
  }

  // 预付款金额校验
  const prepayItem = modalPaymentDetails.value.find((item) => item.value === 'PREPAY')
  if (prepayItem) {
    if (new BigNumber(prepayItem.amount).lte(0)) {
      validationMessage.value = '预付款金额必须大于0'
      return
    }
    if (new BigNumber(prepayItem.amount).gt(props.accountBalance)) {
      validationMessage.value = `预付款金额不能超过账户余额（${props.accountBalance}元）`
      return
    }

    // 预付款不足时提示组合
    if (new BigNumber(prepayItem.amount).lt(props.orderAmount) && modalPaymentDetails.value.length < 2) {
      validationMessage.value = '余额不足，请组合结算'
      return
    }
  }

  // 非独占项金额校验
  const hasExclusive = modalPaymentDetails.value.some((item) => ['ZERO', 'DEPOSIT'].includes(item.value))
  if (!hasExclusive && !new BigNumber(remainingAmount.value).isEqualTo(0)) {
    validationMessage.value = `还有 ${remainingAmount.value} 元未分配`
    return
  }
}

// 打开弹窗（修复：初始化时如果外部值为空，则内部也为空）
const openModal = () => {
  // 核心修复：只有外部有值时才同步，否则保持空数组
  if (props.value && props.value.length > 0) {
    modalPaymentDetails.value = props.value.map((item) => {
      const option = paymentOptions.find((opt) => opt.paytype === item.paytype)
      let amount = item.amount

      // 强制设置独占项金额
      if (option?.value === 'ZERO') amount = 0
      if (option?.value === 'DEPOSIT') amount = new BigNumber(props.orderAmount).toNumber()

      return {
        value: option?.value,
        paytype: item.paytype,
        label: option?.label,
        amount: amount
      }
    })
  } else {
    modalPaymentDetails.value = [] // 确保初始为空
  }

  validateAll()
  visible.value = true
}

// 关闭弹窗
const closeModal = () => {
  visible.value = false
  validationMessage.value = ''
}

// 确认选择
const handleConfirm = () => {
  confirmLoading.value = true

  const result = modalPaymentDetails.value.map((item) => ({
    paytype: item.paytype,
    amount: new BigNumber(item.amount || 0).toNumber() // 添加 || 0 防止NaN
  }))

  emit('update:value', result)
  emit('change', result)

  setTimeout(() => {
    confirmLoading.value = false
    closeModal()
  }, 300)
}

// 取消
const handleCancel = () => {
  closeModal()
}
</script>

<style scoped lang="less">
.payment-type-selector {
  width: 100%;
}

.selector-trigger {
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  padding: 0px 12px;
  background: #fff;
  cursor: pointer;
  transition: all 0.3s;
  min-height: 34px;
  display: flex;
  align-items: center;

  &:hover {
    border-color: #1890ff;
  }

  &.has-error {
    border-color: #ff4d4f;
  }

  .trigger-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;

    .placeholder {
      color: #bfbfbf;
      font-size: 14px;
    }

    .selected-text {
      color: #262626;
      font-size: 14px;
      flex: 1;
    }

    .arrow-icon {
      color: #8c8c8c;
      font-size: 12px;
      margin-left: 8px;
    }
  }
}

.modal-content {
  .amount-summary {
    display: flex;
    gap: 24px;
    margin-bottom: 20px;
    padding: 12px;
    background: #f6f8fa;
    border-radius: 6px;

    .summary-item {
      .label {
        font-size: 13px;
        color: #666;
      }
      .value {
        font-size: 16px;
        font-weight: 500;
      }
    }
  }

  .payment-allocation-list {
    .payment-item {
      border: 1px solid #f0f0f0;
      border-radius: 6px;
      padding: 12px;
      margin-bottom: 12px;
      transition: all 0.3s;

      &:hover {
        border-color: #d9d9d9;
      }

      &.selected {
        border-color: #1890ff;
        background: #f6f8ff;
      }

      &.disabled {
        opacity: 0.5;
        cursor: not-allowed;
      }

      .checkbox-wrapper {
        margin-bottom: 8px;

        .payment-name {
          display: inline-flex;
          align-items: center;
          gap: 8px;
          font-size: 14px;
          font-weight: 500;

          .status-badge {
            font-size: 12px;
            padding: 2px 8px;
            background: #52c41a;
            color: #fff;
            border-radius: 4px;
          }
        }
      }

      .amount-input-wrapper {
        padding-left: 24px;
        display: flex;
        align-items: center;
        gap: 8px;
        flex-wrap: wrap;

        .input-label {
          font-size: 13px;
          color: #666;
        }

        .system-tip {
          font-size: 12px;
          color: #999;
          font-style: italic;
        }
      }

      .balance-warning-inline {
        padding-left: 24px;
        margin-top: 4px;
      }
    }
  }

  .validation-message {
    margin-top: 16px;
    padding: 8px 12px;
    background: #fff2f0;
    border-radius: 4px;
  }
}
</style>
